export const getSelector = (selector: any, ctx?: Document) => {
    ctx = ctx ? ctx : document;
    if (!selector) {
        return null;
    }

    if (typeof selector === "string") {
        selector = selector.replace("/\n/mg", "").trim();
        return ctx.querySelector(selector);
    }

    return selector;
};

export const getSelectorAll = (selector: any, ctx?: Document) => {
    ctx = ctx ? ctx : document;
    if (!selector) {
        return null;
    }

    if (typeof selector === "string") {
        selector = selector.replace("/\n/mg", "").trim();
        return ctx.querySelectorAll(selector);
    }

    return selector;
};

export const hasClass = (elem: Element, className: string) => {
    if (!className) {
        return false;
    }
    return elem.className.match(new RegExp(`(\\s|^)${className}(\\s|$)`));
}


export const getDelateTargetByClassName = (elem: Element, str: string) => {
    const re = new RegExp("(\\s|^)" + str + "(\\s|$)", "i");
    let parent = elem;
    while (parent && !re.test(parent.className)) { // Array.from(parent.classList).includes(str)
        parent = parent.parentNode as HTMLElement;
    }
    return parent ? parent : null;
}


/*
 * 频率控制 返回函数连续调用时，fn 执行频率限定为每多少时间执行一次
 * @param fn {function}  需要调用的函数
 * @param delay  {number}    延迟时间，单位毫秒
 * @param immediate  {bool} 给 immediate参数传递false 绑定的函数先执行，而不是delay后后执行。
 * @return {function}	实际调用函数
 */
export function throttle(fn: Function, delay: number, immediate: boolean, debounce?: boolean) {
    let curr = +new Date(), //当前时间
        last_call = 0,
        last_exec = 0,
        timer: any = null,
        diff, //时间差
        context: any, //上下文
        args: any,
        exec = function () {
            last_exec = curr;
            fn.apply(context, args);
        };
    return function (this: any) {
        curr = +new Date();
        context = this;
        args = arguments;
        diff = curr - (debounce ? last_call : last_exec) - delay;
        clearTimeout(timer);

        if (debounce) {
            if (immediate) {
                timer = setTimeout(exec, delay);
            } else if (diff >= 0) {
                exec();
            }
        } else {
            if (diff >= 0) {
                exec();
            } else if (immediate) {
                timer = setTimeout(exec, -diff);
            }
        }

        last_call = curr;
    };
}

const __uniqueData: any[] = [];
export function generateUniqueData(): string {
    let newData = new Date().getTime() + Math.random().toString(36).slice(2);
     // 生成随机数，可根据需要修改范围
    if (!__uniqueData.includes(newData)) {
        __uniqueData.push(newData);
        return newData;
    } else {
        return this.__generateUniqueData(); // 如果生成的数据已存在，则递归调用函数重新生成
    }
}